# 根据遗传距离矩阵构建进化树
# https://cloud.tencent.com/developer/article/1776443
library(ape)
library(poppr)
library(phangorn)

args <- commandArgs()

path_prefix=args[6]
tree_type=args[7]

# Load data
dist_df <- read.table(paste0(path_prefix, ".mdist"), header=F, sep = ' ')
df_no_na <- dist_df[, apply(dist_df, 2, function(y) any(!is.na(y)))]
df_no_na[is.na(df_no_na)] <- 1

dist_matrix <- as.matrix(df_no_na)

# Add sample name
dist_id <- read.table(paste0(path_prefix, ".mdist.id"), header=F, sep = '\t')
rownames(dist_matrix) = dist_id[,1]

# transform to dist
dist_obj <- as.dist(dist_matrix)

make.tree <- function(dist_obj, filename, tree_type, width, height) {
  if (tree_type == "NJ") {
    tree <- nj(dist_obj)
  } else {
    tree <- upgma(dist_obj)
  }
  write.tree(tree, paste0(filename, ".", tree_type,".tree"))
  pdf(paste0(filename, ".", tree_type, ".tree.pdf"), family = "serif", width = width, height = height)
  par(mar = c(1, 1, .5, .5))
  plot(ladderize(tree))
  add.scale.bar(length = 0.1, font = 1)
  dev.off()
}

make.tree(
  dist_obj,
  path_prefix,
  tree_type,
  40,
  50
)
